package com.fsy.task.gui;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import com.fsy.task.APIController;
import com.fsy.task.APIController2;
import com.fsy.task.domain.ImportUser;
import com.fsy.task.util.Constant;
import com.fsy.task.util.JacksonUtil;
import com.fsy.task.util.UserImportUtil;
import org.htmlparser.util.ParserException;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static javax.swing.JOptionPane.OK_CANCEL_OPTION;
import static javax.swing.JOptionPane.QUESTION_MESSAGE;

/**
 *
 * @author vincent
 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        this.setTitle("\u65b0\u9526\u6210\u770b\u8bfe\u6d4b\u8bd5\u6d4b\u8bc4\u7ba1\u7406\u7cfb\u7edf\u0056\u0031\u002e\u0030");
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        importAnswerB = new JButton();
        timeoutField = new JTextField();
        timeoutField.setColumns(8);
        jLabel =  new JLabel("\u9875\u9762\u8d85\u65f6\u8bbe\u7f6e\u003a");
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);



        jButton2.setText("\u5bfc\u5165\u5b66\u751f\u5bf9\u5e94\u8d26\u53f7");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    jButton2ActionPerformed(evt);
                } catch (IOException e) {
                    JOptionPane.showOptionDialog( Main.this , "\u5bfc\u5165\u5931\u8d25  " + e.getMessage() , "\u901a\u77e5" , OK_CANCEL_OPTION , QUESTION_MESSAGE , null , null , null);
                    //e.printStackTrace();
                }
            }
        });

        importAnswerB.setText("\u5bfc\u5165\u8bd5\u9898\u7b54\u6848");
        importAnswerB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    JFileChooser jFileChooser = new JFileChooser();
                    setDesktopIfWindows(jFileChooser);
                    jFileChooser.showOpenDialog(Main.this);

                    if(jFileChooser.getSelectedFile() != null){
                        APIController.answersCache = JacksonUtil.objectMapper.readValue(
                                new File(jFileChooser.getSelectedFile().getAbsolutePath())
                                , List.class);
                    }
                } catch (IOException e) {
                    //handle the exception
                }
            }
        });
        jButton3.setText("\u5f00\u59cb");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(52, 52, 52)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jButton3)
                                        .addComponent(importAnswerB)
                                        .addComponent(jButton2)
                                        .addComponent(jLabel)
                                        .addComponent(timeoutField)
                                )

                        )
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(importAnswerB)
                                .addGap(18 ,18 ,18)
                                .addComponent(jButton2)
                                .addGap(54, 54, 54)
                                .addComponent(jLabel)
                                .addGap(18 ,18 ,18)
                                .addComponent(timeoutField)
                                .addGap(18 ,18 ,18)
                                .addComponent(jButton3)
                                .addContainerGap(123, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton3ActionPerformed(ActionEvent evt) {
        startDo();
    }



    private void startDo() {
        Constant.TIMEOUT = Integer.valueOf(this.timeoutField.getText().toString());
        if(APIController.userList == null && APIController.userList.size() ==0){
            System.out.println("\u672a\u5bfc\u5165\u5b66\u751f\u4fe1\u606f");
            return;
        }else
            for(ImportUser user : APIController.userList){
                try {
                    APIController2 api = new APIController2(  user.getUsername() , user.getPassword());
                    api.run();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParserException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    }


    public void setDesktopIfWindows(JFileChooser chooser){
        chooser.setCurrentDirectory(new File(System.getenv("HOME") + "/Desktop"));
        chooser.setDragEnabled(true);
    }
    private void jButton2ActionPerformed(ActionEvent evt) throws IOException {
        JFileChooser jFileChooser = new JFileChooser();
        setDesktopIfWindows(jFileChooser);
        jFileChooser.showOpenDialog(this);
        if(jFileChooser.getSelectedFile() != null){
            APIController.userList = UserImportUtil.getImportUserList(jFileChooser.getSelectedFile().getAbsolutePath());
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;

    private JLabel jLabel;
    private JTextField timeoutField;
    private JButton importAnswerB;
    // End of variables declaration
}

